<template>
  <div class="search-container">
    <form action="/">
      <van-search
        v-model="searchText"
        class="search-input"
        placeholder="请输入搜索关键词"
        show-action
        @focus="isResultShow = false"
        @search="onSearch"
        @cancel="$router.back()"
      />
    </form>
    <search-result
      v-if="isResultShow"
      class="search-result"
      :searchText="searchText"
    ></search-result>
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @update-text="onSearch"
    ></search-suggestion>
    <search-history
      v-else
      :searchHistoryLists="searchHistoryLists"
      @update-text="onSearch"
      @delete-histories="searchHistoryLists = []"
    >
    </search-history>
  </div>
</template>
<script>
import searchSuggestion from './components/search-suggestion'
import searchHistory from './components/search-history'
import searchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
import { mapState } from 'vuex'
export default {
  name: 'searchIndex',
  data () {
    return {
      // 控制搜索结果的显示状态
      isResultShow: false,
      // 搜索输入框的内容
      searchText: '',
      searchHistoryLists: getItem('search-history') || []
    }
  },
  components: {
    searchSuggestion,
    searchHistory,
    searchResult
  },
  computed: {
    ...mapState(['user'])
  },
  methods: {
    onSearch (searchText) {
      // 点击联想搜索关键词, 搜索数据
      this.searchText = searchText
      // 保存搜索历史
      this.searchHistoryLists.unshift(this.searchText)
      if (!this.user) {
        // 非登录状态保存本地搜索历史 , 用户搜索历史,当搜索成功时自动保存至后端
        setItem('search-history', this.searchHistoryLists)
      }
      // 展示搜索结果
      this.isResultShow = true
    }
  }
}
</script>
<style lang="less">
</style>
